package com.minhua.jijiehao2.utils;

import android.app.Activity;

import java.util.Stack;

/**
 * activity 栈理
 */
public class ActivityTaskManager {
    private static Stack<Activity> activityStack;
    private static ActivityTaskManager instance;

    private ActivityTaskManager() {

    }

    public static int getSize() {
        return activityStack.size();
    }

    public static ActivityTaskManager getActivityTaskManager() {
        if (instance == null) {
            instance = new ActivityTaskManager();
        }
        return instance;
    }

    /**
     * activity的onCreate中调用
     */
    public void createActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<>();
        }
        activityStack.add(activity);
    }

    /**
     * activity的onFinish中调用
     */
    public void destroyActivity(Activity activity) {
        if (activity != null && activityStack.contains(activity)) {
            activityStack.remove(activity);
        }
    }

    public void finishActivity(Activity activity) {
        if (activity != null) {
            activity.finish();
            activityStack.remove(activity);
            activity = null;
        }
    }

    public Activity currentActivity() {
        Activity activity = activityStack.lastElement();
        return activity;
    }

    public void finishAllActivityExceptOne(Class cls) {
        for (int i = 0; i < activityStack.size(); i++) {
            Activity activity = activityStack.get(i);
            if (activity == null) {
                continue;
            }
            if (activity.getClass().equals(cls)) {
                continue;
            }
            finishActivity(activity);
        }
    }

    public boolean finishAllActivity() {
        for (int i = 0; i < activityStack.size(); i++) {
            Activity activity = activityStack.get(i);
            if (activity == null) {
                continue;
            }
            finishActivity(activity);
            i--;
        }
        return true;
    }
}